Java + Selenium + Chrome抓取页面元素(支持Linux环境和Windows环境)

Java + Selenium + Chrome抓取页面元素(支持Linux环境和Windows环境)

九月 19, 2020 阅读数(请刷新)

前言

尝试过Htmlunit和PhantomJS都无法抓取JS动态生成的页面,这两种方式实际抓取的都是原页面并不是js渲染之后的页面,后来经过尝试终于确定 Selenium + Chrome的方式能抓取js渲染之后的界面,其中也有不少坑,在这里记录一下。

一、下载chromedriver

chromedriver和谷歌版本需要严格对应
下载地址chromedriver
根据谷歌版本下载对应的chromedriver

依赖,高版本的selenium依赖只需要第一个,不用第二个依赖,但经过尝试 ,高版本的依赖可能会出现问题

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.11.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>24.1-jre</version>
</dependency>

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class webdriver {
public static void main(String[] args){
System.getProperties().setProperty("webdriver.chrome.driver",
"D:\\web_driver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
// 无界面参数,使用后不会打开浏览器,linuxx环境必须加入
options.addArguments("--headless");
//禁用沙盒
options.addArguments("--no-sandbox");
options.addArguments("--disable-gpu");
options.addArguments("--disable-dev-shm-usage");
WebDriver webDriver = new ChromeDriver(options);
// webDriver.manage().window().maximize();
webDriver.get("https://www.baidu.com/");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(webDriver.getPageSource());
webDriver.close();

}

}

有一块代码相当重要

1
2
3
4
5
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}

没有这段代码获取到的页面是未渲染的页面

二、linux环境

linux环境:centos7+,内核版本 _x86
centos7以下版本装不上chrome,linux内核为aarch64也装不上

1
2
查看linux内核版本
uname -a

安装chrome

配置chrome yum下载源:
在目录 /etc/yum.repos.d/ 下新建文件 google-chrome.repo

1
touch google-chrome.repo

在google-chrome.repo添加内容

1
2
3
4
5
6
7
8
9
#编辑google-chrome.repo
vi /etc/yum.repos.d/google-chrome.repo
#添加内容
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub

安装chrome

1
yum -y install google-chrome-stable --nogpgcheck

linux环境对不上的可能会报缺少依赖的错误
安装目录在/usr/bin/下

查看安装的chrome版本

1
/usr/bin/google-chrome -version

安装chromedriver
根据上面的chromedriver链接查看对应的chromedriver下载地址

1
2
3
4
5
6
7
8
#使用wget命令下载,这是85.0.4183版本谷歌对应的 driver
wget https://cdn.npm.taobao.org/dist/chromedriver/85.0.4183.87/chromedriver_linux64.zip
#使用unzip 命令解压
unzip chromedriver_linux64.zip
#将chromedriver 移至/usr/bin目录
mv chromedriver /usr/bin/chromedriver
#赋予权限
chomod 777 chromedriver

完成

!!!注意

上面的代码不能直接在liunx环境用,实用上面的代码只能获取到为渲染的页面
要获取到渲染后的页面必须在

1
webDriver.get("https://www.baidu.com/");

这段代码前加上

1
2
3
4
5
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}

完成